//
//  K2DHistrogram.m
//  Kia
//
//  Created by Andrey on 27/04/2009.
//  Copyright 2009 Karma Software. All rights reserved.
//

#import "K2DHistrogram.h"
#import "KImage.h"
#import	"KPixel.h"

NSUInteger IntervalForValue(CGFloat value, NSUInteger intervalCount)
{
	NSUInteger interval = (NSUInteger)(intervalCount * value);
	if (interval >= intervalCount)
		interval = intervalCount - 1;
	
	assert(interval < intervalCount);
	
	return interval;
}

void AddValuesTo2DHistogram(NSUInteger* histogramData, 
						 NSUInteger intervalCount, 
						 CGFloat a, CGFloat b, 
						 NSUInteger* maxPixelsPerInterval)
{
	NSUInteger intervalForA = IntervalForValue(a, intervalCount);
	NSUInteger intervalForB = IntervalForValue(b, intervalCount);
	NSUInteger index = intervalForB * intervalCount + intervalForA;
	
	histogramData[index]++;
	
	if (histogramData[index] > *maxPixelsPerInterval)
		*maxPixelsPerInterval = histogramData[index];
}

@implementation K2DHistrogram

- (void) computeForImage: (KImage*)image
{
	for (int i = 0; i < channelCount; i++)
	{
		bzero(channelHistograms[i].data, sizeof(NSUInteger) * intervalCount);
		channelHistograms[i].maxPixelsPerInterval = 0;
		channelHistograms[i].mean = 0.0;
		channelHistograms[i].variance = 0.0;
	}
	
	ForEachImagePixel(image)
	{
		KRedundantColorVector colorVector = 
		[[image pixelAtX:x y:y] redundantColorVector];
		
		AddValuesTo2DHistogram(channelHistograms[0].data, 
							(NSUInteger)sqrt(intervalCount), 
							colorVector.data[AImageChannel],
							colorVector.data[BImageChannel],
							&channelHistograms[0].maxPixelsPerInterval);
	}
	
	square = image.width * image.height;
	
//	[self computeStatistics];
}

@end
